package org.sao.security.core;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.sao.security.core.properties.SecurityProperties;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class ExecutorConfiguration extends AsyncConfigurerSupport {

	@Autowired
	private SecurityProperties securityProperties;

	@Override
	@Bean(name = "zyTaskExecutor")
	public Executor getAsyncExecutor() {
		// TODO Auto-generated method stub
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(securityProperties.getAsync().getCorePoolSize());
		executor.setMaxPoolSize(securityProperties.getAsync().getMaxPoolSize());
		executor.setQueueCapacity(securityProperties.getAsync().getQueueCapacity());
		executor.setKeepAliveSeconds(securityProperties.getAsync().getKeepAliveSeconds());
		executor.setThreadNamePrefix("zy-executor-");
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		return executor;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		// TODO Auto-generated method stub
		return new SimpleAsyncUncaughtExceptionHandler();
	}

}
